package FileUtils

import (
	"encoding/csv"
	"fmt"
	"github.com/xuri/excelize/v2"
	"log"
	"os"
)

// ReadCsvFile 读取CSV文件转为二维数组
func ReadCsvFile(filePath string) ([][]string, error) {
	file, err := os.Open(filePath)
	if err != nil {
		log.Println("文件转化失败...", err)
		return nil, err
	}
	defer func(file *os.File) {
		err := file.Close()
		if err != nil {
			log.Printf("关闭失败:%s", err)
		}
	}(file)
	reader := csv.NewReader(file)
	records, err := reader.ReadAll()
	if err != nil {
		log.Printf("%s文件读取失败", filePath)
	}
	return records, nil
	//return file,nil
}

// WriteCsvFile 二维数组写入CSV文件
func WriteCsvFile(filePath string, records [][]string) string {
	file, _ := os.Create(filePath)
	defer func(file *os.File) {
		err := file.Close()
		if err != nil {
			log.Printf(err.Error())
		}
	}(file)
	writer := csv.NewWriter(file)
	err := writer.WriteAll(records)
	if err != nil {
		return "Fail"
	} else {
		return "Success"
	}
}

// ReadExcelFile filePath 文件名, sheetPage 读取页数-1为全部
func ReadExcelFile(filePath string, sheetPage int) ([][]string, error) {
	file, err := excelize.OpenFile(filePath)
	if err != nil {
		return nil, err
	}
	defer func(file *excelize.File) {
		err := file.Close()
		if err != nil {
			log.Printf(err.Error())
		}
	}(file)
	var data [][]string
	if sheetPage == -1 {
		sheets := file.GetSheetList()
		for _, sheet := range sheets {
			rows, err := file.GetRows(sheet)
			if err != nil {
				return nil, err
			}
			for _, row := range rows {
				data = append(data, row)
			}
		}
	} else {
		sheet := file.GetSheetList()[sheetPage]
		rows, err := file.GetRows(sheet)
		if err != nil {
			return nil, err
		}
		for _, row := range rows {
			data = append(data, row)
		}
	}
	return data, nil
}

func WriteExcelFile(filePath string, records [][]string) string {
	fw := excelize.NewFile()
	sheet := "sheet1"
	for i, row := range records {
		for j, cell := range row {
			cellName := fmt.Sprintf("%c%d", 'A'+j, i+1)
			err := fw.SetCellValue(sheet, cellName, cell)
			if err != nil {
				log.Printf(err.Error())
				return "Fail"
			}
		}
	}
	err := fw.SaveAs(filePath)
	if err != nil {
		log.Printf(err.Error())
		return "Fail"
	}
	return "Success"
}
